import time
from loguru import logger
import requests
from tybase.tools import ali_oss_tools
import os
from datetime import datetime
from urllib.parse import quote


def upload_file_to_aliyun(cloud_file_path: str, loc_target_path: str):
    # 这些参数可以从环境变量或者配置文件中读取，以增加安全性
    access_id = 'LTAI5tAZqRCwXzraoCyLmogg'
    access_key = 'ATFqOuECljzrhUPV9VsYKRaXUQknmt'
    bucket_name = 'ty-huanlian'
    endpoint = 'http://oss-cn-shanghai.aliyuncs.com'
    # 实例化阿里云的对象
    co = ali_oss_tools.ConnectOss(access_id, access_key, endpoint, bucket_name)
    # 上传文件到阿里云，并获取返回的路径
    return co.upload_file(cloud_file_path, loc_target_path)


# 这里云的命名转换
def transform_path(file_path, folder_name="swap_face"):
    # 从原始路径中提取文件名
    loc_name = os.path.basename(file_path)

    # 获取当前年份和月份
    current_date = datetime.now()
    year = current_date.year
    month = current_date.month

    # 构建新路径, swap_face是阿里云的保存目录
    new_path = f"{folder_name}/{year}{str(month).zfill(2)}/{loc_name}"

    return new_path

def main_upload_file_to_aliyun(loc_target_path: str):
    cloud_file_path = transform_path(loc_target_path, folder_name="swap_face")
    return upload_file_to_aliyun(cloud_file_path, loc_target_path)
    

from qiniu import Auth, put_file


class QiniuTools:
    def __init__(self, access_key, secret_key, bucket_name):
        self.q = Auth(access_key, secret_key)
        self.bucket_name = bucket_name

    def upload_file(self, cloud_file_path, loc_target_path):
        # 生成上传Token
        token = self.q.upload_token(self.bucket_name, cloud_file_path)
        # 调用上传方法
        ret, info = put_file(token, cloud_file_path, loc_target_path)
        if ret:
            # 这里简单返回文件名作为成功上传的标志，实际应用中你可以根据需要修改
            return cloud_file_path
        else:
            raise Exception("Upload to Qiniu failed!")


def upload_file_to_qiniu(cloud_file_path: str, loc_target_path: str):
    # 这些参数可以从环境变量或者配置文件中读取，以增加安全性
    access_key = 'CuEf0CRuGsO5Vu6wQ3b-3dwyJeaVXVN5blOyoOJQ'
    secret_key = 'jHY3PiaGmGepPr-pwKsBRVPTGu7ZCWFfGFBnzfUD'
    bucket_name = 'tyushow'

    # 实例化七牛云的对象
    qn = QiniuTools(access_key, secret_key, bucket_name)
    res_path = qn.upload_file(cloud_file_path, loc_target_path)

    # 上传文件到七牛云，并获取返回的路径
    return quote(res_path, safe='')  # 这里确保所有字符都被编码

def main_upload_file_to_qiniu(loc_target_path: str):
    cloud_file_name = transform_path(loc_target_path, folder_name="swap_face")
    return upload_file_to_qiniu(cloud_file_name, loc_target_path)



def notify_cloud(task):
    url = "http://api.gpuhub.xiaolubi.com/task/queue/completion"  # 修改了gpu的地址
    headers = {
        "TOKEN": "inUVBuypkgdmm5ym6l3XiIMwenb7SKQu"
    }
    data = {
        "queue_id": task.id,
        "status": 100 if task.status == "completed" else 250,
        "error_message": ""
    }
    try:
        if not task.result:
            logger.error(f"task的result为空")
            data["result"] = {}
            data["status"] = 250
            data["error_message"] = "其他错误"
        elif task.status == "failed":
            data["status"] = 250
        elif data["error_message"]:
            data["status"] = 250
        data["result"] = task.result

    except Exception as e:
        data["result"] = {}
        data["status"] = 250
        data["error_message"] = f"系统其他错误{str(e)[:200]}"
        import traceback
        traceback.print_exc()
        logger.error(f'Notify failed due to: {str(e)}')

    # 做3次通知的尝试
    for i in range(3):
        try:
            response = requests.post(url, json=data, headers=headers)
            logger.success(f"{response.status_code} -> 通知成功!")
            logger.info(f"data: {data}")
            # logger.info(f"result: {task.result}")
            logger.debug(f"response: {response.json()}")
            break
        except Exception as e:
            time.sleep(2)
            print("失败...开始尝试重新尝试..",e)
            continue
        
        
    
def notify_cloud_v2(result,task_id,status,error_message):
    from loguru import logger
    from config import notify_token,notify_url
    # logger.debug(result)
    url = notify_url
    headers = {
        "TOKEN": notify_token
    }
    data = {
        "queue_id": task_id,
        "status": status,
        "error_message": error_message,
        "result": result
    }
    
    for i in range(3):
        try:
            response = requests.post(url, json=data, headers=headers)
            logger.success(f"{response.status_code} -> 通知成功!")
            logger.info(f"data: {data}")
            logger.debug(f"response: {response.json()}")
            break
        except Exception as e:
            time.sleep(2)
            print("失败...开始尝试重新尝试..",e)
            continue